package com.android.happymall.fragment.member;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.happymall.R;
import com.android.happymall.activity.GoodsDetailActivity;
import com.android.happymall.activity.mine.LoginActivity;
import com.android.happymall.model.auction.AuctionActivityData;
import com.android.happymall.model.auction.AuctionActivitySendData;
import com.android.happymall.model.auction.AuctionResultData;
import com.android.happymall.model.auction.Auction_DetailRecentlyData;
import com.android.happymall.model.auction.Auction_DetailRecentlySendData;
import com.android.happymall.model.auction.Auction_JoinBackData;
import com.android.happymall.model.auction.Auction_JoinSendData;
import com.android.happymall.model.auction.UpdateAuctionBean;
import com.android.happymall.model.group.DirectBuyData;
import com.android.happymall.model.group.DirectBuyDataCallback;
import com.android.happymall.service.WebSocketService1;
import com.android.happymall.service.WebSocketService3;
import com.android.happymall.utils.ConstantsUrl;
import com.android.happymall.utils.HttpUtils;
import com.android.happymall.utils.LoginState;
import com.android.happymall.utils.MyLog;
import com.android.happymall.utils.ObjectUtils;
import com.android.happymall.view.MyGridView;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by Administrator on 2017/11/17.
 */

public class Fragment33 extends Fragment {


    @BindView(R.id.sort_listview)
    ListView listview;
    @BindView(R.id.listView)
    MyGridView gridview;
    @BindView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout mRefreshLayout;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.no_data)
    RelativeLayout noData;
    //    @BindView(R.id.sort_viewpager)
//    ViewPager viewPager;
    @BindView(R.id.main_top_title)
    TextView mainTopTitle;
    @BindView(R.id.main_top_bg)
    Toolbar mainTopBg;
    private FragmentActivity mcontext;
    //    private GroupFragmentPagerAdapters pagerAdapter;
    private BaseAdapter adapter1;
    private AdaptList adapter ;
    private View view;
    private LayoutInflater inflater;
    private boolean networkConnected;
    private Auction_DetailRecentlyData recentlyData = new Auction_DetailRecentlyData();
    private Auction_DetailRecentlySendData recentlySendData = new Auction_DetailRecentlySendData();
    private String currentid;
    private Auction_JoinSendData auction_joinSendData = new Auction_JoinSendData();
    private AuctionActivitySendData auctionActivitySendData = new AuctionActivitySendData();
    private AuctionActivityData auctionactivitydata;
    private Auction_JoinBackData auction_joinBackData = new Auction_JoinBackData();
    private AuctionResultData auctionResultData = new AuctionResultData();
    private HashMap<String,ViewHolder> myViewHolderList = new HashMap<>();
    private HashMap<String,Boolean> isStartMap = new HashMap<>();
    private HashMap<String,Boolean> isMostMap = new HashMap<>();
    private HashMap<String,UpdateAuctionBean> updateBean = new HashMap<>();
    private HashMap<String,UpdateAuctionBean> lastperiodBean = new HashMap<>();
    private LinearLayoutManager layoutmanager = new LinearLayoutManager(mcontext);
    private ArrayList<AuctionActivityData.ListBean> listdata = new ArrayList<>();
    private ArrayList<AuctionActivityData.ListBean> temporary_listdata = new ArrayList<>();
    private Gson gson = new Gson();
    private String gsonstring="";
    private WebSocketService1 service;
    private BroadcastReceiver mBroadcastReceiver;

    private String cid="0";
    private int page=1;
    private int mid;
    private String token;
    private int currentcid;
    protected boolean isLoad = false;
    private Message message,message2,message3,message4;
    private boolean isStartThread = false;
    private ArrayList<DirectBuyData.DataBean> cat_list = new ArrayList<>();
    public Fragment33() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        this.inflater = inflater;
        view = inflater.inflate(R.layout.fragment_fragment33, container, false);
        mcontext = getActivity();
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        ButterKnife.bind(this, view);
        mainTopTitle.setText("全部商品");
        mainTopTitle.setTextColor(Color.parseColor("#ffffff"));
        mainTopBg.setBackgroundColor(Color.parseColor("#FF2741"));
        if(!LoginState.getInstance().getid(mcontext).equals("")&&LoginState.getInstance().getid(mcontext)!=null) {
            mid = Integer.parseInt(LoginState.getInstance().getid(mcontext));
            token = LoginState.getInstance().getUserInfo(mcontext,2);
        }
        initRecycle();
        ReFreshData();
        /**初始化的时候去加载数据**/
        if(!isStartThread) {
            handler1.post(mRunnable);
            isStartThread =true;
        }
        myViewHolderList.clear();
        temporary_listdata.clear();
        broadcastReceive();
        initData();
        GetDataListData();
        isLoad = true;
        return view;
    }
    @Override
    public void onResume()
    {
        super.onResume();
        if(!LoginState.getInstance().getid(mcontext).equals("")&&LoginState.getInstance().getid(mcontext)!=null) {
            mid = Integer.parseInt(LoginState.getInstance().getid(mcontext));
            token = LoginState.getInstance().getUserInfo(mcontext,2);
            // SetDou();

        }
    }

    protected void initData() {

        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            auctionActivitySendData.setType("get_auctions");
            auctionActivitySendData.setPage(page);
            auctionActivitySendData.setPer_page(100);
            auctionActivitySendData.setCid(Integer.parseInt(cid));
            gsonstring = gson.toJson(auctionActivitySendData);
            service.setCid(cid);
            service.sendMsg(gsonstring);

        } else {


            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
        }
    }
    private void initRecycle() {
        adapter = new AdaptList(mcontext,listdata);
        gridview.setAdapter(adapter);
       // adapter.setLoadMoreView(new CustomLoadMoreView());
        //  adapter.setOnLoadMoreListener(this,mRecyclerView);
     //  mRecyclerView.setLayoutManager(layoutmanager);
      //  mRecyclerView.setAdapter(adapter);
        //mRecyclerView.GetToTop((ImageView) view.findViewById(R.id.top), 0);
//        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
//            @Override
//            public void onItemClick(BaseQuickAdapter adapter1, View view, int position) {
//                Intent intent = new Intent(mcontext, GoodsDetailActivity.class);
//                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_SHOW, 1);
//                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_ID,temporary_listdata.get(position).getId());
//                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_COMMON_ID, "");
//                startActivityForResult(intent, 1);
//            }
//        });
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //currentid = temporaryf1_listdata.get(position).getId();
                if (LoginState.getInstance().isLogin(mcontext)) {
                    Intent intent = new Intent(mcontext, GoodsDetailActivity.class);
                    intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_SHOW, 1);
                    intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_ID,listdata.get(position).getId());
                    intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_COMMON_ID,"");
                    startActivityForResult(intent,1);
                }
                else
                {
                    startActivityForResult(new Intent(mcontext, LoginActivity.class),2);
                }
            }
        });
//        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
//            @Override
//            public boolean onItemChildClick(BaseQuickAdapter adapter1, View view, int position) {
//                switch (view.getId()) {
//                    case R.id.rightnow_openteam:
//                        if (LoginState.getInstance().isLogin(mcontext)) {
//                            auction_joinSendData.setType("join_auction");
//                            auction_joinSendData.setId(Integer.parseInt(adapter.getData().get(position).getId()));
//                            auction_joinSendData.setMid(mid);
//                            auction_joinSendData.setToken(token);
//                            gsonstring = gson.toJson(auction_joinSendData);
//                            service.sendMsg(gsonstring);
//                        }
//                        else
//                        {
//                            startActivity(new Intent(mcontext, LoginActivity.class));
//                        }
//                        break;
//
//                }
//                return false;
//            }
//        });
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                cid=cat_list.get(i).getId();
                page = 1;
                myViewHolderList.clear();
                temporary_listdata.clear();
                listdata.clear();
                auctionActivitySendData.setType("get_auctions");
                auctionActivitySendData.setPage(page);
                auctionActivitySendData.setPer_page(100);
                auctionActivitySendData.setCid(Integer.parseInt(cid));
                gsonstring = gson.toJson(auctionActivitySendData);
                service.setCid(cid);
                service.sendMsg(gsonstring);
                currentcid = i;
                adapter1.notifyDataSetChanged();
            }
        });
    }
    private void ReFreshData() {
        if (mRefreshLayout != null) {

            mRefreshLayout.setColorSchemeResources(R.color.app_title);
            mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    networkConnected = ObjectUtils.isNetworkConnected(mcontext);
                    if (networkConnected) {
                        mRefreshLayout.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                page = 1;
                                myViewHolderList.clear();
                                temporary_listdata.clear();
                                listdata.clear();
                                auctionActivitySendData.setType("get_auctions");
                                auctionActivitySendData.setPage(page);
                                auctionActivitySendData.setPer_page(100);
                                auctionActivitySendData.setCid(Integer.parseInt(cid));
                                gsonstring = gson.toJson(auctionActivitySendData);
                                service.setCid(cid);
                                service.sendMsg(gsonstring);
                            }
                        }, 1000);
                    } else {
                        ObjectUtils.toast(mcontext, "网络连接出现异常");
                        mRefreshLayout.setRefreshing(false);
                    }
                }
            });
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode)
        {
            case 1:
                if(data!=null) {
                    // 获取传递的数据
                    MyLog.e("dddd","ffff");
                    Bundle bundle = data.getExtras();
                    // 获得返回值
                    String id = bundle.getString("auction_id");
                    String period = bundle.getString("auction_period");
                    recentlySendData.setType("join_log");
                    String order_sn = id + "_" + period;
                    recentlySendData.setOrder_sn(order_sn);
                    recentlySendData.setPage(1);
                    recentlySendData.setPer_page(2);
                    gsonstring = gson.toJson(recentlySendData);
                    service.sendMsg(gsonstring);
                }
                break;
        }
    }
    @OnClick(R.id.click_resetnetwork_refresh)
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.click_resetnetwork_refresh:
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 3);
                page = 1;
                myViewHolderList.clear();
                temporary_listdata.clear();
                listdata.clear();
                auctionActivitySendData.setType("get_auctions");
                auctionActivitySendData.setPage(page);
                auctionActivitySendData.setPer_page(100);
                auctionActivitySendData.setCid(Integer.parseInt(cid));
                gsonstring = gson.toJson(auctionActivitySendData);
                service.setCid(cid);
                service.sendMsg(gsonstring);
                break;

        }
    }
    //
//    @Override
//    public void onLoadMoreRequested() {
//        page = page + 1;
//        auctionActivitySendData.setType("get_auctions");
//        auctionActivitySendData.setPage(page);
//        auctionActivitySendData.setPer_page(10);
//        auctionActivitySendData.setCid(Integer.parseInt(cid));
//        gsonstring = gson.toJson(auctionActivitySendData);
//        service.setCid(cid);
//        service.sendMsg(gsonstring);
//    }
    //设置广播监听
    private void broadcastReceive()
    {

        service = WebSocketService1.getInstance();
        // service.sendMsg(get_menus);
        mBroadcastReceiver = new BroadcastReceiver(){
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                //更新竞买返回消息
                if(action.equals(WebSocketService1.ACTION_NOT1)){
                    Intent intents = mcontext.getIntent();
                    auctionResultData = (AuctionResultData)intent.getBundleExtra("bundle").getSerializable("AuctionResult");
                    if(auctionResultData!=null)
                    {
                        DealWithResult();
                    }
                }

                //更新商品列表
                if(action.equals(WebSocketService1.ACTION_AUCTION1))
                {
                    noData.setVisibility(View.GONE);
                    boolean isUpdateUsername =false;
                    auctionactivitydata = (AuctionActivityData) intent.getBundleExtra("bundle2").getSerializable("AuctionGetAuctions");
                    if(auctionactivitydata.getList()!=null&&auctionactivitydata.getList().size()>0) {
                        int midd=0;
//                        if(auctionactivitydata.getList().get(0).getMid()!=null)
//                        {
//                            midd = Integer.parseInt(auctionactivitydata.getList().get(0).getMid());
//                        }
//                        if(midd>0)
//                        {
//                            isUpdateUsername =true;
//                        }
                        listdata = new ArrayList<>();
                        if(page==1)
                        {
                            temporary_listdata.clear();
                        }
                        for (int i = 0; i < auctionactivitydata.getList().size(); i++) {
//                            if(isUpdateUsername)
//                            {
////                                   if (auctionactivitydata.getList().get(i).getUsername() != null && !auctionactivitydata.getList().get(i).getUsername().equals(""))
////                                   {
////                                       currentlyUser.put(auctionactivitydata.getList().get(i).getId(), auctionactivitydata.getList().get(i).getUsername());
////                                   }
//                            }
//                            else {

                            temporary_listdata.add(new AuctionActivityData.ListBean(AuctionActivityData.ListBean.THREE, auctionactivitydata.getList().get(i).getId()
                                    , auctionactivitydata.getList().get(i).getPeriod(), auctionactivitydata.getList().get(i).getTitle()
                                    , auctionactivitydata.getList().get(i).getThumb(), auctionactivitydata.getList().get(i).getPrice()
                                    , auctionactivitydata.getList().get(i).getTime(), auctionactivitydata.getList().get(i).getStart()
                                    , auctionactivitydata.getList().get(i).getMid(), auctionactivitydata.getList().get(i).getUsername()));
                            listdata.add(new AuctionActivityData.ListBean(AuctionActivityData.ListBean.THREE, auctionactivitydata.getList().get(i).getId()
                                    , auctionactivitydata.getList().get(i).getPeriod(), auctionactivitydata.getList().get(i).getTitle()
                                    , auctionactivitydata.getList().get(i).getThumb(), auctionactivitydata.getList().get(i).getPrice()
                                    , auctionactivitydata.getList().get(i).getTime(), auctionactivitydata.getList().get(i).getStart()
                                    , auctionactivitydata.getList().get(i).getMid(), auctionactivitydata.getList().get(i).getUsername()));
                            //用于存储标识是否有start时间的map
                            if (auctionactivitydata.getList().get(i).getStart() != 0)
                            {
                                isStartMap.put(auctionactivitydata.getList().get(i).getId(), true);
                            }
                            else {
                                isStartMap.put(auctionactivitydata.getList().get(i).getId(), false);
                            }
                            //用于存储标识是否是最高价的map
                            if(auctionactivitydata.getList().get(i).getMid()!=null&&!auctionactivitydata.getList().get(i).getMid().equals(""))
                            {
                                if(auctionactivitydata.getList().get(i).getMid().equals(mid+"")) {
                                    isMostMap.put(auctionactivitydata.getList().get(i).getId(), true);
                                }
                                else
                                {
                                    isMostMap.put(auctionactivitydata.getList().get(i).getId(),false);
                                }
                            }
                            else
                            {
                                isMostMap.put(auctionactivitydata.getList().get(i).getId(), false);
                            }
                            //用于存储标识是否更新数据的map
                            updateBean.put(auctionactivitydata.getList().get(i).getId(),new UpdateAuctionBean());
                            lastperiodBean.put(auctionactivitydata.getList().get(i).getId(),new UpdateAuctionBean());
                            // }
                        }
//                        if(isUpdateUsername)
//                        {
//                            //  handler1.post(mRunnable3);
//                        }
//                        else
//                        {

                        AdapterListData();
                        //}
                    }
                    else
                    {
                        if(page==1)
                        {
                            noData.setVisibility(View.VISIBLE);
                        }

                    }

                }
                //趣买最新出价（判断自己当前出价是否为最高）
                if (action.equals(WebSocketService3.ACTION_JOINLOG)) {
                    recentlyData = (Auction_DetailRecentlyData) intent.getBundleExtra("bundle5").getSerializable("AuctionJoinLog");

                    if(recentlyData.getList()!=null&&recentlyData.getList().size()>0) {
                        if(recentlyData.getList().get(0).getMid().equals(mid+"")) {
                            isMostMap.put(currentid, true);
                            Message message = new Message();
                            message.what = 5;
                            handler1.sendMessage(message);
                        }
                    }
                }
                //更新商品竞买时间，价格，出价人
                if(action.equals(WebSocketService1.ACTION_JOINBACK1))
                {
                    auction_joinBackData = (Auction_JoinBackData)intent.getBundleExtra("bundle3").getSerializable("AuctionJoinBack");
                    String code = auction_joinBackData.getCode();
                    if(code!=null&&!code.equals(""))
                    {
                        if(Integer.parseInt(code)>0)
                        {
                            ObjectUtils.toast(mcontext,auction_joinBackData.getMsg());
                        }
                    }

                    if(temporary_listdata!=null) {
                        boolean isupdateusername = false;
                        for (int i = 0; i < temporary_listdata.size(); i++) {
                            int id = Integer.parseInt(temporary_listdata.get(i).getId());
                            if (auction_joinBackData.getId() == id) {
                                if(auction_joinBackData.getUsername()!=null&&auction_joinBackData.getPrice()>0)
                                {
                                    isupdateusername = true;
                                    isMostMap.put(temporary_listdata.get(i).getId(),false);
                                    UpdateAuctionBean update = new UpdateAuctionBean();
                                    update.setUsername(auction_joinBackData.getUsername());
                                    update.setPrice(auction_joinBackData.getPrice());
                                    updateBean.put(temporary_listdata.get(i).getId(),update);
                                    if(auction_joinBackData.getTime()>0)
                                    {
                                        temporary_listdata.get(i).setTime(auction_joinBackData.getTime());
                                    }
                                    if(auction_joinBackData.getMid()>0)
                                    {
                                        temporary_listdata.get(i).setMid(auction_joinBackData.getMid()+"");
                                    }
                                    break;
                                }
                            }
                        }
                        if(isupdateusername)
                        {
                            handler1.post(mRunnable3);
                        }
                    }
                }
//                   if(action.equals(WebSocketService.ACTION_Nav))
//                   {
//                       navData= (Auction_NavData) intent.getBundleExtra("bundle2").getSerializable("AuctionNav");
//                       GetMenus();
//                   }

            }
        };
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(WebSocketService3.ACTION_JOINLOG);
        myIntentFilter.addAction(WebSocketService1.ACTION_NOT1);
        myIntentFilter.addAction(WebSocketService1.ACTION_AUCTION1);
        myIntentFilter.addAction(WebSocketService1.ACTION_JOINBACK1);

        // myIntentFilter.addAction(WebSocketService.ACTION_Nav);
        //注册广播
        mcontext.registerReceiver(mBroadcastReceiver, myIntentFilter);
    }
    /**
     * 处理竞买返回通知消息
     */
    private void DealWithResult()
    {
        /**
         * 趣买返回通知重开
         */
        if(auctionResultData.getTime()>0&&auctionResultData.getStart()>0)
        {
            /**
             * 更新重开的商品时间
             */
            if (temporary_listdata != null) {
                for (int i = 0; i < temporary_listdata.size(); i++) {
                    String id = temporary_listdata.get(i).getId();
                    if (auctionResultData.getId().equals(id)) {
                        temporary_listdata.get(i).setTime(auctionResultData.getTime());
                        temporary_listdata.get(i).setStart(auctionResultData.getStart());
                        if(auctionResultData.getStart()>0) {
                            isStartMap.put(temporary_listdata.get(i).getId(), true);
                        }
                        isMostMap.put(temporary_listdata.get(i).getId(), false);
                        break;
                    }
                }
            }
            /**
             * 有人中拍时
             */
            if(auctionResultData.getMid()>0)
            {
                /**
                 * 更新上期中拍商品活动状态和数据
                 */
                UpdateAuctionBean update = new UpdateAuctionBean();
                update.setUsername(auctionResultData.getUsername());
                update.setIspass_in(false);
                lastperiodBean.put(auctionResultData.getId()+"",update);
                handler1.post(mRunnable4);
            }
            /**
             * 无人中拍时
             */
            else
            {
                /**
                 * 更新上期流拍商品活动状态
                 */
                UpdateAuctionBean update = new UpdateAuctionBean();
                update.setIspass_in(true);
                lastperiodBean.put(auctionResultData.getId()+"",update);
                handler1.post(mRunnable4);
            }
        }
        /**
         * 竞买返回通知不重开
         */
        else
        {
            /**
             *
             */
//           if(auction_style.equals("mine_auctioning")) {
//               if (listdata != null) {
//                   for (int i = 0; i < listdata.size(); i++) {
//                       int id = Integer.parseInt(listdata.get(i).getId());
//                       if (auctionResultData.getId() == id) {
//                           listdata.remove(i);
//                           break;
//                       }
//                   }
//               }
//               if (myViewHolderList.containsKey(auctionResultData.getId())) {
//                   myViewHolderList.remove(auctionResultData.getId());
//               }
//           }
            /**
             * 有人中拍时
             */
            if(auctionResultData.getMid()>0)
            {
                /**
                 * 头条
                 */
                String content = "恭喜" +auctionResultData.getUsername()+"以"
                        +"<font color='#FF0000'>"+"¥"+auctionResultData.getLast_price()+"</font>"+"拼购到"
                        +"<font color='#99ccff'>"+auctionResultData.getTitle()+"</font>";
                /**
                 * 更新上期中拍商品活动状态和数据
                 */
                UpdateAuctionBean update = new UpdateAuctionBean();
                update.setUsername(auctionResultData.getUsername());
                update.setIspass_in(false);
                lastperiodBean.put(auctionResultData.getId()+"",update);
                handler1.post(mRunnable4);
            }
            /**
             * 无人中拍时
             */
            else
            {
                /**
                 * 更新上期流拍商品活动状态
                 */
                UpdateAuctionBean update = new UpdateAuctionBean();
                update.setIspass_in(true);
                lastperiodBean.put(auctionResultData.getId()+"",update);
                handler1.post(mRunnable4);
            }
        }
    }
    /**
     * 适配商品列表
     */
    private void AdapterListData()
    {
        mRefreshLayout.setRefreshing(false);
        ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
        adapter = new AdaptList(mcontext,listdata);
        gridview.setAdapter(adapter);

        adapter.notifyDataSetChanged();
//        if (page == 1) {
//
//            MyLog.e("111",listdata.size()+"");
//            adapter.setNewData(listdata);
//
//            if (auctionactivitydata.getList().size() < 10 ) {
//                adapter.loadMoreComplete();
//                adapter.loadMoreEnd();
//            }
//        } else {
//            MyLog.e("112221",listdata.size()+"");
//            adapter.addData(listdata);
//            adapter.loadMoreComplete();
//        }
        // mRecyclerView.setAdapter(adapter);
    }
    private Handler handler1 = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case 1:
                    adapter.notifyTimeData();
                    break;
                case 2:
                    adapter.notifyDataSetChanged();
                    break;
                case 3:
                    adapter.notifyUsernameData();
                    break;
                case 4:
                    adapter.notifyLastPeriod();
                    break;
                case 5:
                    adapter.notifyMostPrice();
                    break;
            }
        }
    };
    //更新上一期活动是否流拍
    private Runnable mRunnable4 = new Runnable() {
        @Override
        public void run() {
            if (null == message4) {
                message4 = new Message();
            } else {
                message4 = Message.obtain();
            }
            message4.what = 4;
            //发送信息给handler
            handler1.sendMessage(message4);
        }
    };
    //更新当前出价和竞拍人
    private Runnable mRunnable3 = new Runnable() {
        @Override
        public void run() {
            if (null == message3) {
                message3 = new Message();
            } else {
                message3 = Message.obtain();
            }
            message3.what = 3;
            //发送信息给handler
            handler1.sendMessage(message3);
        }
    };
    //更新商品是否过期
    private Runnable mRunnable2 = new Runnable() {
        @Override
        public void run() {
            if (null == message2) {
                message2 = new Message();
            } else {
                message2 = Message.obtain();
            }
            message2.what = 2;
            //发送信息给handler
            handler1.sendMessage(message2);
        }
    };
    //更新商品时间
    private Runnable mRunnable = new Runnable(){

        @Override
        public void run() {
            if( temporary_listdata!=null) {
                for (int i = 0; i <  temporary_listdata.size(); i++) {

                    int time =  temporary_listdata.get(i).getTime();
                    int start =  temporary_listdata.get(i).getStart();
                    if (start > 0) {
                        start = start - 1;
                        temporary_listdata.get(i).setStart(start);
                    }
                    if (time > 0) {
                        time = time - 1;
                        temporary_listdata.get(i).setTime(time);

                    }
                }
            }
            if (null == message) {
                message = new Message();
            } else {
                message = Message.obtain();
            }
            message.what = 1;
            //发送信息给handler
            handler1.sendMessage(message);
            //每1000豪秒重启一下线程
            handler1.postDelayed(mRunnable, 1000);
        }
    };

    private void GetDataListData()
    {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain + ConstantsUrl.MAIN_GOODSCATEGORYDATA ;
        if (networkConnected) {

            HttpUtils.get(address,null, new DirectBuyDataCallback() {

                @Override
                public void onError(Call call, Exception e, int id) {
                }

                @Override
                public void onResponse(DirectBuyData response, int id) {

                    if (response.getCode() == 0) {

                        if (response.getData() != null) {
                            if ( response.getData()!=null){
                                cat_list.clear();
                                cat_list.add(new DirectBuyData.DataBean("0","全部商品","","","","",""));
                                cat_list.addAll(response.getData());
                                adapter1 = new BaseAdapter() {
                                    @Override
                                    public int getCount() {
                                        return cat_list.size();
                                    }

                                    @Override
                                    public Object getItem(int i) {
                                        return cat_list.get(i);
                                    }

                                    @Override
                                    public long getItemId(int i) {
                                        return i;
                                    }

                                    @Override
                                    public View getView(int i, View view, ViewGroup viewGroup) {
                                        if(view==null) {
                                            view = inflater.inflate(R.layout.item_fragment3_listview, null);
                                        }
                                        LinearLayout ll = (LinearLayout) view.findViewById(R.id.ll);
                                        View v = (View)view.findViewById(R.id.view);
                                        TextView tv_name= (TextView) view.findViewById(R.id.tv);
                                        tv_name.setText(cat_list.get(i).getCatname());
                                        if(currentcid==i)
                                        {
                                            v.setVisibility(View.VISIBLE);
                                            tv_name.setTextColor(getResources().getColor(R.color.app_title));
                                            ll.setBackgroundResource(R.drawable.corner_white_bg);
                                        }
                                        else
                                        {
                                            tv_name.setTextColor(getResources().getColor(R.color.black));
                                            v.setVisibility(View.GONE);
                                            ll.setBackgroundResource(R.drawable.corner_gray_bg2);
                                        }
                                        return view;
                                    }
                                };
                                listview.setAdapter(adapter1);
                            }
                        }
                    }else {

                    }
                }
            });

        } else{

            ObjectUtils.toast(mcontext, "网络未连接");
        }
    }
    public class AdaptList extends  BaseAdapter {
        private LayoutInflater Inflater;
        private Context content;
        private List<AuctionActivityData.ListBean> listdata;

        public AdaptList(Context content, List<AuctionActivityData.ListBean> listdata) {
            this.listdata = listdata;
            this.content = content;
            this.Inflater = LayoutInflater.from(content);
        }

        @Override
        public int getCount() {
            return listdata==null? 0:listdata.size();
        }
        @Override
        public Object getItem(int position) {
            return null;
        }
        @Override
        public long getItemId(int position) {
            return 0;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder holder = null;
            holder = new ViewHolder();
            if (convertView == null) {
                convertView = Inflater.inflate(R.layout.item_grid_aishangmainpage, null);
                holder.time_position = position;
                holder.kill_minute = (TextView) convertView.findViewById(R.id.kill_minute);
                holder.kill_second = (TextView) convertView.findViewById(R.id.kill_second);
                holder.kill_millsecond = (TextView) convertView.findViewById(R.id.kill_millsecond);
                holder.item_rightnow_price = (TextView) convertView.findViewById(R.id.item_rightnow_price);
                holder.rightnow_openteam = (TextView) convertView.findViewById(R.id.rightnow_openteam);
                holder.item_lastperiod_person = (TextView) convertView.findViewById(R.id.item_lastperiod_person);
                holder.item_lastperiod_person= (TextView) convertView.findViewById(R.id.item_lastperiod_person);
                holder.item_grid_detail_like_title = ( TextView) convertView.findViewById(R.id.item_grid_detail_like_title);
                holder.item_lastperiod_failed = ( LinearLayout) convertView.findViewById(R.id.item_lastperiod_failed);
                holder.item_lastperiod_ll = ( LinearLayout) convertView.findViewById(R.id.item_lastperiod_ll);
                holder.item_rightnow_ll = ( LinearLayout) convertView.findViewById(R.id.item_rightnow_ll);
                holder.item_rightnow_default = (TextView)convertView.findViewById(R.id.item_rightnow_default);
                holder.item_grid_aishang_img = (ImageView) convertView.findViewById(R.id.item_grid_aishang_img);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            final AuctionActivityData.ListBean mainlistdata = listdata.get(position);
            if(!(myViewHolderList.containsKey(mainlistdata.getId()))) {
                myViewHolderList.put(mainlistdata.getId(),holder);
            }
            int time1 = mainlistdata.getTime();
            String minute1 = String.format("%02d", time1/ 3600);
            String second1 = String.format("%02d", time1  % 3600 / 60);
            String millsecond1 = String.format("%02d", time1% 60);
            holder.kill_millsecond.setText(millsecond1);
            holder.kill_minute.setText( minute1);
            holder.kill_second.setText(second1);
            ObjectUtils.photo2(content, mainlistdata.getThumb(), ((ImageView) holder.item_grid_aishang_img));
            holder.item_rightnow_price.setText("当前价: ￥" + mainlistdata.getPrice());
            holder.item_grid_detail_like_title.setText(mainlistdata.getTitle());
//            if(temporaryf1_listdata!=null)
//            {
//                for (int i = 0; i <  temporaryf1_listdata.size(); i++) {
//                    int time = temporaryf1_listdata.get(i).getTime();
//                    int start = temporaryf1_listdata.get(i).getStart();
//                    if (myViewHolderList.containsKey(temporaryf1_listdata.get(i).getId())) {
//                        boolean isstart = isStartMap.get(temporaryf1_listdata.get(i).getId());
//                        boolean isMost = isMostMap.get(temporaryf1_listdata.get(i).getId());
//                        //有start时间时
//                        if (isstart) {
//                            myViewHolderList.get(temporaryf1_listdata.get(i).getId()).rightnow_openteam.setText("即将开始");
//                            myViewHolderList.get(temporaryf1_listdata.get(i).getId()).rightnow_openteam.setEnabled(false);
//                            myViewHolderList.get(temporaryf1_listdata.get(i).getId()).rightnow_openteam.setBackgroundResource(R.drawable.corner_yellow_bg2);
//                            String minute = String.format("%02d", start / 3600);
//                            String second = String.format("%02d", start % 3600 / 60);
//                            String millsecond = String.format("%02d", start % 60);
//                            myViewHolderList.get(temporaryf1_listdata.get(i).getId()).kill_millsecond.setText(millsecond);
//                            myViewHolderList.get(temporaryf1_listdata.get(i).getId()).kill_minute.setText(minute);
//                            myViewHolderList.get(temporaryf1_listdata.get(i).getId()).kill_second.setText(second);
//                            if (start == 0) {
//                                myViewHolderList.get(temporaryf1_listdata.get(i).getId()).rightnow_openteam.setText("立即拼购");
//                                myViewHolderList.get(temporaryf1_listdata.get(i).getId()).rightnow_openteam.setBackgroundResource(R.drawable.corner_red_bg2);
//                                myViewHolderList.get(temporaryf1_listdata.get(i).getId()).item_rightnow_default.setVisibility(View.VISIBLE);
//                                myViewHolderList.get(temporaryf1_listdata.get(i).getId()).item_lastperiod_failed.setVisibility(View.GONE);
//                                myViewHolderList.get(temporaryf1_listdata.get(i).getId()).item_lastperiod_ll.setVisibility(View.GONE);
//                                myViewHolderList.get(temporaryf1_listdata.get(i).getId()).rightnow_openteam.setEnabled(true);
//                                isStartMap.put(temporaryf1_listdata.get(i).getId(), false);
//                            }
//                        }
//                        //没有start时间时
//                        else {
//                            String minute = String.format("%02d", time / 3600);
//                            String second = String.format("%02d", time % 3600 / 60);
//                            String millsecond = String.format("%02d", time % 60);
//                            myViewHolderList.get(temporaryf1_listdata.get(i).getId()).kill_millsecond.setText(millsecond);
//                            myViewHolderList.get(temporaryf1_listdata.get(i).getId()).kill_minute.setText(minute);
//                            myViewHolderList.get(temporaryf1_listdata.get(i).getId()).kill_second.setText(second);
//                            if (time > 0) {
//                                if (!isMost) {
//                                    myViewHolderList.get(temporaryf1_listdata.get(i).getId()).rightnow_openteam.setText("立即拼购");
//                                    myViewHolderList.get(temporaryf1_listdata.get(i).getId()).rightnow_openteam.setBackgroundResource(R.drawable.corner_red_bg2);
//                                    myViewHolderList.get(temporaryf1_listdata.get(i).getId()).rightnow_openteam.setEnabled(true);
//
//                                } else {
//                                    myViewHolderList.get(temporaryf1_listdata.get(i).getId()).rightnow_openteam.setText("你已最高");
//                                    myViewHolderList.get(temporaryf1_listdata.get(i).getId()).rightnow_openteam.setBackgroundResource(R.drawable.corner_gray_bg2);
//                                    myViewHolderList.get(temporaryf1_listdata.get(i).getId()).rightnow_openteam.setEnabled(false);
//                                }
//                            }
//                            if (time == 0) {
//                                myViewHolderList.get(temporaryf1_listdata.get(i).getId()).kill_millsecond.setText("00");
//                                myViewHolderList.get(temporaryf1_listdata.get(i).getId()).kill_minute.setText("00");
//                                myViewHolderList.get(temporaryf1_listdata.get(i).getId()).kill_second.setText("00");
//                                myViewHolderList.get(temporaryf1_listdata.get(i).getId()).rightnow_openteam.setText("出价结束");
//                                myViewHolderList.get(temporaryf1_listdata.get(i).getId()).rightnow_openteam.setBackgroundResource(R.drawable.corner_gray_bg2);
//                            }
//
//                        }
//                    }

            //}}

            return convertView;

        }
        //更新当前出价竞拍人
        public void notifyUsernameData() {
            if( temporary_listdata!=null) {

                for (int i = 0; i <  temporary_listdata.size(); i++) {
                    String id =  temporary_listdata.get(i).getId();
                    if (myViewHolderList.containsKey(id)) {
                        if(updateBean.get(id).getPrice()>0) {
                            isMostMap.put(id,false);
                            myViewHolderList.get(id).item_lastperiod_failed.setVisibility(View.GONE);
                            myViewHolderList.get(id).item_rightnow_default.setVisibility(View.GONE);
                            myViewHolderList.get(id).item_lastperiod_ll.setVisibility(View.VISIBLE);
                            myViewHolderList.get(id).item_lastperiod_person.setText("ID: "+updateBean.get(id).getUsername());
                            myViewHolderList.get(id).item_rightnow_price.setText("当前价: ￥" + updateBean.get(id).getPrice());
                            myViewHolderList.get( temporary_listdata.get(i).getId()).rightnow_openteam.setText(R.string.app_fragment3_keyname);
                            myViewHolderList.get(temporary_listdata.get(i).getId()).rightnow_openteam.setBackgroundResource(R.drawable.corner_red_bg2);
                            myViewHolderList.get(temporary_listdata.get(i).getId()).rightnow_openteam.setEnabled(true);
                        }
                    }
                }
            }
        }
        //更新商品活动最高价
        public void notifyMostPrice() {
            if(temporary_listdata!=null) {
                for (int i = 0; i <  temporary_listdata.size(); i++) {
                    Auction_DetailRecentlyData data = recentlyData;
                    String id = temporary_listdata.get(i).getId();
                    if (myViewHolderList.containsKey(id)&&temporary_listdata.get(i).getMid()!=null&&!temporary_listdata.get(i).getMid().equals("")) {

                        if(temporary_listdata.get(i).getMid().equals(data.getList().get(0).getMid())) {
                            isMostMap.put(id, true);
                            myViewHolderList.get(id).item_lastperiod_failed.setVisibility(View.GONE);
                            myViewHolderList.get(id).item_rightnow_default.setVisibility(View.GONE);
                            myViewHolderList.get(id).item_lastperiod_ll.setVisibility(View.VISIBLE);
                            myViewHolderList.get(id).item_lastperiod_person.setText("ID: "+data.getList().get(0).getUsername());
                            myViewHolderList.get(id).item_rightnow_price.setText("当前价: ￥" + data.getList().get(0).getPrice());
                            myViewHolderList.get(id).rightnow_openteam.setText("你已最高");
                            myViewHolderList.get(temporary_listdata.get(i).getId()).rightnow_openteam.setBackgroundResource(R.drawable.corner_gray_bg2);
                            myViewHolderList.get(temporary_listdata.get(i).getId()).rightnow_openteam.setEnabled(false);
                        }
                    }
                }
            }
        }
        //更新上期商品活动是否失效
        public void notifyLastPeriod() {
            if(temporary_listdata!=null) {
                for (int i = 0; i <  temporary_listdata.size(); i++) {
                    String id = temporary_listdata.get(i).getId();
                    if(auctionResultData.getId().equals(id)) {
                        if (myViewHolderList.containsKey(id)) {
                            myViewHolderList.get(id).item_rightnow_price.setText("当前价: ￥0");
                            myViewHolderList.get( temporary_listdata.get(i).getId()).rightnow_openteam.setText(R.string.app_fragment3_keyname);
                            myViewHolderList.get(temporary_listdata.get(i).getId()).rightnow_openteam.setBackgroundResource(R.drawable.corner_red_bg2);
                            myViewHolderList.get(temporary_listdata.get(i).getId()).rightnow_openteam.setEnabled(true);
                            if (lastperiodBean.get(id).ispass_in()) {
                                myViewHolderList.get(id).item_rightnow_default.setVisibility(View.GONE);
                                myViewHolderList.get(id).item_lastperiod_failed.setVisibility(View.VISIBLE);
                                myViewHolderList.get(id).item_lastperiod_ll.setVisibility(View.GONE);
                            } else {
                                myViewHolderList.get(id).item_lastperiod_failed.setVisibility(View.GONE);
                                myViewHolderList.get(id).item_rightnow_default.setVisibility(View.GONE);
                                myViewHolderList.get(id).item_lastperiod_ll.setVisibility(View.VISIBLE);
                                myViewHolderList.get(id).item_lastperiod_person.setText("上期拼购到: " + lastperiodBean.get(id).getUsername());
                            }
                        }
                    }
                }
            }
        }
        //更新全部商品时间
        public void notifyTimeData(){

            if( temporary_listdata!=null) {

                for (int i = 0; i <  temporary_listdata.size(); i++) {
                    int time =  temporary_listdata.get(i).getTime();
                    int start =  temporary_listdata.get(i).getStart();


                    if (myViewHolderList.containsKey( temporary_listdata.get(i).getId())) {
                        boolean isstart = isStartMap.get(temporary_listdata.get(i).getId());
                        boolean isMost = isMostMap.get(temporary_listdata.get(i).getId());
                        //有start时间时
                        if (isstart) {
                            myViewHolderList.get(temporary_listdata.get(i).getId()).rightnow_openteam.setText("即将开始");
                            myViewHolderList.get(temporary_listdata.get(i).getId()).rightnow_openteam.setEnabled(false);
                            myViewHolderList.get(temporary_listdata.get(i).getId()).rightnow_openteam.setBackgroundResource(R.drawable.corner_yellow_bg2);
                            String minute = String.format("%02d", start / 3600);
                            String second = String.format("%02d", start % 3600 / 60);
                            String millsecond = String.format("%02d", start % 60);
                            myViewHolderList.get(temporary_listdata.get(i).getId()).kill_millsecond.setText(millsecond);
                            myViewHolderList.get(temporary_listdata.get(i).getId()).kill_minute.setText(minute);
                            myViewHolderList.get(temporary_listdata.get(i).getId()).kill_second.setText(second);
                            if (start == 0) {
                                myViewHolderList.get(temporary_listdata.get(i).getId()).rightnow_openteam.setText(R.string.app_fragment3_keyname);
                                myViewHolderList.get(temporary_listdata.get(i).getId()).rightnow_openteam.setBackgroundResource(R.drawable.corner_red_bg2);
                                myViewHolderList.get(temporary_listdata.get(i).getId()).item_rightnow_default.setVisibility(View.VISIBLE);
                                myViewHolderList.get(temporary_listdata.get(i).getId()).item_lastperiod_failed.setVisibility(View.GONE);
                                myViewHolderList.get(temporary_listdata.get(i).getId()).item_lastperiod_ll.setVisibility(View.GONE);
                                myViewHolderList.get(temporary_listdata.get(i).getId()).rightnow_openteam.setEnabled(true);
                                isStartMap.put(temporary_listdata.get(i).getId(), false);
                            }
                        }
                        //没有start时间时
                        else {

                            String minute = String.format("%02d", time / 3600);
                            String second = String.format("%02d", time % 3600 / 60);
                            String millsecond = String.format("%02d", time % 60);
                            myViewHolderList.get(temporary_listdata.get(i).getId()).kill_millsecond.setText(millsecond);
                            myViewHolderList.get(temporary_listdata.get(i).getId()).kill_minute.setText(minute);
                            myViewHolderList.get(temporary_listdata.get(i).getId()).kill_second.setText(second);
                            if (time > 0) {
                                if (!isMost) {
                                    myViewHolderList.get(temporary_listdata.get(i).getId()).rightnow_openteam.setText(R.string.app_fragment3_keyname);
                                    myViewHolderList.get(temporary_listdata.get(i).getId()).rightnow_openteam.setBackgroundResource(R.drawable.corner_red_bg2);
                                    myViewHolderList.get(temporary_listdata.get(i).getId()).rightnow_openteam.setEnabled(true);

                                } else {
                                    myViewHolderList.get(temporary_listdata.get(i).getId()).rightnow_openteam.setText("你已最高");
                                    myViewHolderList.get(temporary_listdata.get(i).getId()).rightnow_openteam.setBackgroundResource(R.drawable.corner_gray_bg2);
                                    myViewHolderList.get(temporary_listdata.get(i).getId()).rightnow_openteam.setEnabled(false);
                                }
                            }
                            if (time == 0) {
                                myViewHolderList.get(temporary_listdata.get(i).getId()).kill_millsecond.setText("00");
                                myViewHolderList.get(temporary_listdata.get(i).getId()).kill_minute.setText("00");
                                myViewHolderList.get(temporary_listdata.get(i).getId()).kill_second.setText("00");
                                myViewHolderList.get(temporary_listdata.get(i).getId()).rightnow_openteam.setText("出价结束");
                                myViewHolderList.get(temporary_listdata.get(i).getId()).rightnow_openteam.setBackgroundResource(R.drawable.corner_gray_bg2);
                                myViewHolderList.get(temporary_listdata.get(i).getId()).rightnow_openteam.setEnabled(false);
                                isMostMap.put(temporary_listdata.get(i).getId(), false);
                            }
                        }
                    }
                }
            }
        }
    }

    static class ViewHolder {
        int time_position;
        TextView kill_minute ;
        TextView kill_second ;
        TextView kill_millsecond ;
        TextView item_rightnow_price;
        TextView rightnow_openteam;
        TextView item_rightnow_default;
        LinearLayout item_lastperiod_failed,item_lastperiod_ll,item_rightnow_ll;
        TextView item_lastperiod_person;
        ImageView item_grid_aishang_img;
        TextView item_grid_detail_like_title;

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        listdata.clear();
        temporary_listdata.clear();
        myViewHolderList.clear();
        service = null;
        handler1.removeCallbacks(mRunnable);
        getActivity().unregisterReceiver(mBroadcastReceiver);
        mBroadcastReceiver  = null;
    }

}

